<?php

namespace App\Jobs\Push;

use Exception;
use App\Facades\Push;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

/**
 * 考勤提醒定时推送任务
 *
 * Date: 2018/6/2
 * @author George
 * @package App\Jobs\Push
 */
class AttendanceRemindPush implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

	/**
	 * 获取定时任务
	 *
	 * Date: 2018/6/2
	 * @author George
	 */
    public function handle()
    {
    	$key = date('Y-m-d H:i', time() + config('system.remind.advance'));
		$singin_schedules = Redis::connection('remind')->hvals("signin_" . $key);
		$singout_schedules = Redis::connection('remind')->hvals("signout_" . $key);

		$singin_ids = Redis::connection('remind')->hkeys("signin_" . $key);
		$singout_ids = Redis::connection('remind')->hkeys("signout_" . $key);

		$title = '考勤提醒';

		$this->send($singin_schedules, $title, config('system.remind.attendance.signin'));
		$this->send($singout_schedules, $title, config('system.remind.attendance.signout'));

		// 删除缓存任务内容
		Redis::connection('remind')->hdel($key, array_merge($singin_ids, $singout_ids));
    }

	/**
	 * Date: 2018/6/2
	 * @author George
	 * @param array $alias
	 * @param string $title
	 * @param string $alert
	 * @param array $extras
	 */
	private function send(array $alias, $title = '', $alert = '', $extras = [])
	{
		// 定义IOS通知样式
		$ios_notification = config('system.push.ios');
		$ios_notification['extras'] = $extras;

		$ios_alert = [
			"title" => $title,
			"body" => $alert,
		];

		// 定义Android通知样式
		$android_notification = config('system.push.android');
		$android_notification['title'] = $title;
		$android_notification['extras'] = $extras;

		try {
			$response = Push::push()->setPlatform('all')
				->addAlias($alias)
				->iosNotification($ios_alert, $ios_notification)
				->androidNotification($alert, $android_notification)
				->setNotificationAlert($alert)
				->options(['apns_production' => config('system.push.apns_production')])
				->send();
			Log::info(json_encode($response));
		} catch (Exception $exception) {
			Log::error($exception);
		}
	}
}
